import {
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Query,
  Sse,
} from '@nestjs/common';
import { ApisService } from './apis.service';
import { interval, Observable } from 'rxjs';
import { ConfigService } from '@nestjs/config';
import OpenAI from 'openai';
@Controller('apis')
export class ApisController {
  constructor(
    private readonly apisService: ApisService,
    private configService: ConfigService,
  ) {}
  @Get('toutiao')
  async getToutiao() {
    return await this.apisService.createToutiao();
  }

  @Get('history')
  async getHistory() {
    return await this.apisService.createHistory();
  }

  @Get('getHistoryList')
  async getHistoryList() {
    return await this.apisService.findAllHistory();
  }

  @Get('getHistoryDetail/:id')
  async getHistoryDetail(@Param('id') id: number) {
    return await this.apisService.getHistoryDetail(id);
  }

  @Get('getToutiaoList')
  async getToutiaoList() {
    return await this.apisService.findAllToutiao();
  }

  @Get('getToutiaoDetail/:id')
  async getToutiaoDetail(@Param('id') id: string) {
    return await this.apisService.getToutiaoDetail(id);
  }

  @Get('getOpenAi/:content')
  @Sse()
  async getOpenAi(@Query('model') model: string, @Query('lastQuestion') lastQuestion: string, @Param('content') content: string): Promise<Observable<any>> {
    const openaiModel = model || 'qwen-plus';
    console.log(openaiModel, 'openaiModel')
    const openai = new OpenAI({
      apiKey: this.configService.get(`${openaiModel}_key`),
      baseURL: this.configService.get(`${openaiModel}_base_url`),
    });
    let completion
    try {
      if (lastQuestion) {
        completion = await openai.chat.completions.create({
          stream: true,
          model: model,
          messages: [
            { role: 'system', content: 'You are a helpful assistant.' },
            { role: 'user', content: lastQuestion },
            { role: 'user', content: content },
          ],
        });
      } else {
        completion = await openai.chat.completions.create({
          stream: true,
          model: model,
          messages: [
            { role: 'assistant', content: 'You are a helpful assistant.' },
            { role: 'user', content: content },
          ],
        });
      }
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new Observable<any>((observer) => {
      // 使用async函数和生成器函数实现流式传输
      async function* stream() {
        try {
          for await (const chunk of completion) {
            if (chunk?.choices?.[0]?.finish_reason === 'stop') {
              observer.next({
                data: 'done:true',
              });
              observer.complete();
            } else {
              observer.next({
                data: chunk?.choices?.[0]?.delta?.content || '',
              });
            }
          }
        } catch (error) {
          observer.error(error); // 发生错误时通知观察者
        }
      }

      stream().next(); // 启动生成器函数
    });
  }
}
